/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.net;

import java.io.IOException;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.rmi.server.RMIClientSocketFactory;

import jp.aist.gtrc.plus.scheduler.specific.pbs.util.PBSAuthenticator;


public class GuardedRMIClientSocketFactory implements RMIClientSocketFactory, Serializable {

	private static final long serialVersionUID = 6757652414320889635L;

	private static final int HASH_CODE = "GuardedRMIClientSocketFactory".hashCode();
	private final String authSrvName;
	private final int authSrvPort;
	private static final int DEFAULT_LOCAL_PORT = 40000;
	private static final int BIND_TRY_MAX = 1000;

	public GuardedRMIClientSocketFactory(String authSrvName, int authServPort) {

		this.authSrvName = authSrvName;
		this.authSrvPort = authServPort;

	}

	public Socket createSocket(String host, int port) throws IOException {

		Socket socket = new Socket();

		try {
			bindLocalPort(socket);
			authenticate(socket);
		} catch (IOException e) {
			try {
				socket.close();
			} catch (IOException ex) {
				// ignore
			}
			throw e;
		}

		socket.connect(new InetSocketAddress(host, port));

		return socket;

	}

	private void bindLocalPort(Socket socket) throws IOException {

		for (int port = DEFAULT_LOCAL_PORT;
			port < DEFAULT_LOCAL_PORT + BIND_TRY_MAX; port++) {
			try {
				socket.bind(new InetSocketAddress(port));
				return;	// if bind() succeeded
			} catch (IOException e) {
				// ignore to next challenge
			}
		}

		throw new IOException("cannot bind, not enough free local port");

	}

	private void authenticate(Socket socket) throws IOException {

		try {
			PBSAuthenticator.authenticate(authSrvName, authSrvPort,
				socket.getLocalPort());
		} catch (Exception e) {
			throw new IOException("socket authentication failed");
		}

	}


	public boolean equals(Object o) {

		return (o instanceof GuardedRMIClientSocketFactory);

	}

	public int hashCode() {

		return HASH_CODE;
	}

}
